
/**
 * 目标1：设置频道下拉菜单
 *  1.1 获取频道列表数据
 *  1.2 展示到下拉菜单中
 */
const formSelect = document.querySelector('.form-select')
// 获取频道列表数据
async function getChannals() {
    await axios({
        url:"/v1_0/channels",
    }).then(res => {
        // console.log(res);
        const channels = res.data.channels;
        // console.log(channels);
        const selectStr = channels.map((item) => {
            return `<option value="${item.id}">${item.name}</option>`
        }).join('');
        formSelect.innerHTML = `<option value="" selected="">请选择文章频道</option>` + selectStr;
    })
}

getChannals();

/**
 * 目标2：文章封面设置
 *  2.1 准备标签结构和样式
 *  2.2 选择文件并保存在 FormData
 *  2.3 单独上传图片并得到图片 URL 网址
 *  2.4 回显并切换 img 标签展示（隐藏 + 号上传标签）
 */

document.querySelector('.img-file').addEventListener('change', e => {
    const file = e.target.files[0];
    if (!file) return;
    const fd = new FormData();
    fd.append('image', file);
    axios({
        url: '/v1_0/upload',
        method: 'POST',
        data: fd,
    }).then(res => {
        console.log(res);
        const imgUrl = res.data.url;
        document.querySelector('.rounded').src = imgUrl;
        document.querySelector('.rounded').classList.add('show');
        document.querySelector('.place').classList.add('hide');
    })
});

document.querySelector('.rounded').addEventListener('click', e => {
    document.querySelector('.img-file').click();
})


/**
 * 目标3：发布文章保存
 *  3.1 基于 form-serialize 插件收集表单数据对象
 *  3.2 基于 axios 提交到服务器保存
 *  3.3 调用 Alert 警告框反馈结果给用户
 *  3.4 重置表单并跳转到列表页
 */

document.querySelector('.send').addEventListener('click',e => {
    if (document.querySelector('.send').innerHTML !== '发布') return;
    const dataObj = serialize(document.querySelector('.art-form'), {hash: true, empty: true});
    const cover = {
        type: 1,
        images: [document.querySelector('.rounded').src],
    }
    dataObj.cover = cover;
    console.log(dataObj);
    axios({
        url: "/v1_0/mp/articles",
        method: "POST",
        data: dataObj,
    }).then(res => {
        console.log(res);
        if (res.message === "OK") {
            myAlert(true, "发布成功");
            setTimeout(() => {
                location.href = "../content/index.html";
            }, 3000); 
            document.querySelector('.art-form').reset();
            document.querySelector('.rounded').src = '';
            document.querySelector('.rounded').classList.remove('show');
            document.querySelector('.place').classList.remove('hide');
            editor.setHtml('');

        }
    }).catch(err => {
        console.log(err);
        myAlert(false, "频道选择有误");
    })

});


/**
 * 目标4：编辑-回显文章
 *  4.1 页面跳转传参（URL 查询参数方式）
 *  4.2 发布文章页面接收参数判断（共用同一套表单）
 *  4.3 修改标题和按钮文字
 *  4.4 获取文章详情数据并回显表单
 */
(function(){
    const paramsStr = location.search;
    const params = new URLSearchParams(paramsStr);
    params.forEach((value, key) => {
        if (key === "id") {
            document.querySelector('.title').innerHTML = `<span>修改文章</span>`;
            document.querySelector('.send').innerHTML = "修改";
            axios({
                url: `/v1_0/mp/articles/${value}`,
            }).then(res => {
                // console.log(res);
                const artObj = {
                    title: res.data.title,
                    channel_id: res.data.channel_id,
                    content: res.data.content,
                    id: res.data.id,
                    rounded: res.data.cover.images[0],
                };
                Object.keys(artObj).forEach(key => {
                    if (key === 'rounded' && res.data.cover.type !== 0) {
                        document.querySelector('.rounded').src = artObj[key];
                        document.querySelector('.rounded').classList.add('show');
                        document.querySelector('.place').classList.add('hide');
                    }else if (key === 'content') {
                        editor.setHtml(artObj[key]);
                    }else {
                        document.querySelector(`[name=${key}]`).value = artObj[key];
                    }
                })
            })
        }
    })
})()

/**
 * 目标5：编辑-保存文章
 *  5.1 判断按钮文字，区分业务（因为共用一套表单）
 *  5.2 调用编辑文章接口，保存信息到服务器
 *  5.3 基于 Alert 反馈结果消息给用户
 */

document.querySelector('.send').addEventListener('click', e => {
    if (document.querySelector('.send').innerHTML !== '修改') return;
    const dataObj = serialize(document.querySelector('.art-form'), {hash: true, empty: true});
    const cover = {
        type: 1,
        images: [document.querySelector('.rounded').src],
    }
    dataObj.cover = cover;
    console.log(dataObj);
    axios({
        url: `/v1_0/mp/articles/${dataObj.id}`,
        method: "PUT",
        data: dataObj,
    }).then(res => {
        console.log(res);
        if (res.message === "OK") {
            myAlert(true, "修改成功");
            setTimeout(() => {
                location.href = "../content/index.html";
            }, 3000); 
            document.querySelector('.art-form').reset();
            document.querySelector('.rounded').src = '';
            document.querySelector('.rounded').classList.remove('show');
            document.querySelector('.place').classList.remove('hide');
            editor.setHtml('');

        }
    }).catch(err => {
        console.log(err);
        myAlert(false, err.response.data.message);
    })
})
